package com.ougy.reshop.dao.impl;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.util.Version;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.stereotype.Repository;

import com.chenlb.mmseg4j.analysis.MaxWordAnalyzer;
import com.ougy.reshop.dao.IPublishDao;
import com.ougy.reshop.model.Publish;

@Repository
public class PublishDao extends BaseDao<Publish> implements IPublishDao {
	private Logger logger = Logger.getLogger(getClass());

	@PostConstruct
	public void doIndex() throws InterruptedException {
		SessionFactory sf = getHibernateTemplate().getSessionFactory();
		Session session = SessionFactoryUtils.getSession(sf,true);
		FullTextSession fullTextSession = Search.getFullTextSession(session);
		fullTextSession.createIndexer().startAndWait();
		fullTextSession.close();
	}

	@Override
	public List<Publish> search(final String queryString,final int pageNo,final int pageSize) {
		List<Publish> searchResult = (List<Publish>) getHibernateTemplate()
				.execute(new HibernateCallback() {
					public Object doInHibernate(org.hibernate.Session session) {
						FullTextSession fullTextSession = Search
								.getFullTextSession(session);
						Transaction tx = fullTextSession.beginTransaction();

						QueryBuilder qb = fullTextSession.getSearchFactory()
								.buildQueryBuilder().forEntity(Publish.class)
								.get();
						org.apache.lucene.search.Query query = qb.keyword()
								.onFields("title", "owner.username").matching(
										queryString).createQuery();

						// wrap Lucene query in a org.hibernate.Query
						org.hibernate.Query hibQuery = fullTextSession
								.createFullTextQuery(query, Publish.class);

						// execute search
						List<Publish> result = hibQuery.list();
						tx.commit();
						
						//高亮设置  
	                    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter( "<font color=\"red\">", "</font>");     
	                    QueryScorer qs = new QueryScorer(query);  
	                    Highlighter highlighter = new Highlighter( formatter, qs);  
	                                          
	                    for(int i = 0; i < result.size(); i++) {  
	                        String findResult = "";  
	                        Publish pub = result.get(i);  
	                        Analyzer analyzer = new MaxWordAnalyzer();      
	                        try {  
	                            findResult = highlighter.getBestFragment(analyzer, queryString, pub.getTitle());  
	                        } catch (InvalidTokenOffsetsException e) {  
	                            e.printStackTrace();  
	                        } catch (IOException e) {
								e.printStackTrace();
							}  
	                        //重新封装  
	                        pub.setTitle(findResult);  
	                    }  
						return result;
					}
				});

		return searchResult;
	}
}
